import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import api from './api'

// 管理员认证状态
const isAdminAuthenticated = ref(false)
const adminPassword = ref('')

// 生成随机密码
const generateRandomPassword = () => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let password = ''
  for (let i = 0; i < 12; i++) {
    password += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return password
}

// 初始化管理员密码
const initAdminPassword = async () => {
  try {
    // 先检查本地存储的密码
    const storedPassword = localStorage.getItem('admin_password')
    if (storedPassword) {
      adminPassword.value = storedPassword
      console.log('使用本地存储的管理员密码')
      return
    }
    
    // 从后端获取真实的管理员密码
    const response = await api.getCurrentAdminPassword()
    if (response.data.success) {
      const realPassword = response.data.password
      adminPassword.value = realPassword
      localStorage.setItem('admin_password', realPassword)
      console.log('从后端获取管理员密码:', realPassword)
    } else {
      throw new Error('获取管理员密码失败')
    }
  } catch (error) {
    console.error('获取管理员密码失败:', error)
    // 如果获取失败，使用本地生成的密码作为备用
    const newPassword = generateRandomPassword()
    adminPassword.value = newPassword
    localStorage.setItem('admin_password', newPassword)
    console.log('使用本地生成的管理员密码:', newPassword)
  }
}

// 验证管理员密码
const verifyAdminPassword = (inputPassword) => {
  return inputPassword === adminPassword.value
}

// 管理员登录
const adminLogin = async (password) => {
  try {
    const response = await api.adminAuth(password)
    
    if (response.data.success) {
      // 登录成功后，同步本地密码
      adminPassword.value = password
      localStorage.setItem('admin_password', password)
      
      isAdminAuthenticated.value = true
      localStorage.setItem('admin_authenticated', 'true')
      localStorage.setItem('admin_token', response.data.token)
      ElMessage.success('管理员登录成功')
      return true
    } else {
      ElMessage.error(response.data.error || '认证失败')
      return false
    }
  } catch (error) {
    console.error('管理员登录失败:', error)
    ElMessage.error('登录失败，请检查网络连接')
    return false
  }
}

// 管理员登出
const adminLogout = () => {
  isAdminAuthenticated.value = false
  localStorage.removeItem('admin_authenticated')
  localStorage.removeItem('admin_token')
  ElMessage.info('已退出管理员模式')
}

// 检查管理员认证状态
const checkAdminAuth = () => {
  const stored = localStorage.getItem('admin_authenticated')
  if (stored === 'true') {
    isAdminAuthenticated.value = true
  }
  return isAdminAuthenticated.value
}

// 获取当前密码（用于显示）
const getCurrentPassword = () => {
  return adminPassword.value
}

// 重新生成密码
const regeneratePassword = async () => {
  try {
    const token = getAdminToken()
    if (!token) {
      ElMessage.error('请先登录管理员账户')
      return null
    }
    
    const response = await api.regenerateAdminPassword()
    
    if (response.data.success) {
      const newPassword = response.data.new_password
      adminPassword.value = newPassword
      localStorage.setItem('admin_password', newPassword)
      // 登出当前管理员
      adminLogout()
      ElMessage.success('密码已重新生成，请重新登录')
      return newPassword
    } else {
      ElMessage.error(response.data.error || '重新生成密码失败')
      return null
    }
  } catch (error) {
    console.error('重新生成密码失败:', error)
    ElMessage.error('重新生成密码失败，请检查网络连接')
    return null
  }
}

// 获取管理员token
const getAdminToken = () => {
  return localStorage.getItem('admin_token')
}

// 初始化
const initializeAuth = async () => {
  try {
    await initAdminPassword()
    checkAdminAuth()
  } catch (error) {
    console.error('初始化认证失败:', error)
  }
}

// 延迟初始化，避免循环依赖
setTimeout(() => {
  initializeAuth()
}, 100)

export {
  isAdminAuthenticated,
  adminLogin,
  adminLogout,
  checkAdminAuth,
  getCurrentPassword,
  regeneratePassword,
  getAdminToken
}
